package com.youlai.boot.system.controller;

import com.youlai.boot.common.result.Result;
import com.youlai.boot.common.util.ClosureRequest;
import com.youlai.boot.config.BatchUpdateRequest;
import com.youlai.boot.system.model.entity.TaskTable;
import com.youlai.boot.system.model.query.TaskTableQuery;
import com.youlai.boot.system.model.vo.TaskTableVO;
import com.youlai.boot.system.service.TaskTableService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import com.youlai.boot.system.model.form.TaskTableForm;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import io.swagger.v3.oas.annotations.Parameter;
import com.youlai.boot.common.result.PageResult;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.metadata.IPage;

@Tag(name = "任务管理模块")
@RestController
@RequestMapping("/api/v1/taskTables")
@RequiredArgsConstructor
public class TaskTableController {
    @Autowired
    private TaskTableService tasktableService;

//    @Operation(summary = "首页分页列表")
//    @GetMapping("/page")
////    @PreAuthorize("@ss.hasPerm('system:tasktable:query')")
//    public PageResult<TaskTableVO> getTasktablePage(TaskTableQuery queryParams) {
//        IPage<TaskTableVO> result = tasktableService.getTasktablePage(queryParams);
//        return PageResult.success(result);
//    }

//    @Operation(summary = "新增任务")
//    @PostMapping("/save")
//    public Result<Void> saveTask(@RequestBody @Valid TaskTableForm taskTableForm) {
//        boolean result = tasktableService.saveTasktable(taskTableForm);
//        return Result.judge(result);
//    }

//    /**
//     * 根据医生id去查询任务
//     *
//     * @param doctorId
//     * @return
//     */
//    @GetMapping("/{doctorId}")
//    public List<TaskTable> getTasksByDoctor(@PathVariable Long doctorId) {
//        return tasktableService.getTasksByDoctorId(doctorId);
//    }
//
//    /**
//     * 查询所有任务
//     *
//     * @return
//     */
//
//    @GetMapping("/all")
//    public Result<List<TaskTable>> listAllTasks() {
//        List<TaskTable> taskTableList = tasktableService.listAllTasks();
//
//        return Result.success(taskTableList);
//    }

    //    @PostMapping("/add")
//    public String addTask(@RequestBody TaskTable task) {
//        taskTableService.addOrUpdateTask(task);
////        return "Task added successfully";
////    }
//    @Operation(summary = "获取首页表单数据")
//    @GetMapping("/{id}/form")
//    @PreAuthorize("@ss.hasPerm('system:tasktable:edit')")
//    public Result<TaskTableForm> getTasktableForm(
//            @Parameter(description = "首页ID") @PathVariable Long id
//    ) {
//        TaskTableForm formData = tasktableService.getTasktableFormData(id);
//        return Result.success(formData);
//    }

    /**
     * 耗时
     *
     * @param id
     * @param request
//     * @return
//     */
//    @PostMapping("/not/{id}")
//    public String setClosure(@PathVariable Integer id, @RequestBody ClosureRequest request) {
//        TaskTable task = tasktableService.getById(id);
//        if (task == null) {
//            return "Task not found";
//        }
//
//        task.setClosure(request.getClosure());
//        task.setState(1); // 假设状态1表示已完成
//        tasktableService.addOrUpdateTask(task);
////        return "Closure time set successfully";
////    }
//
//    /**
//     * 剩余时间
//     *
//     * @param id
//     * @return
//     */
//
//    @GetMapping("/update/{id}")
//    public String updateRemainingTime(@PathVariable Integer id) {
//        tasktableService.updateRemainingTime(id);
//        return "Remaining time updated successfully";
//    }
//
//    @Operation(summary = "修改")
//    @PutMapping(value = "/{id}")
//    //@PreAuthorize("@ss.hasPerm('system:tasktable:edit')")
//    public Result<Void> updateTasktable(
//            @Parameter(description = "首页ID") @PathVariable Long id,
//            @RequestBody @Valid TaskTableForm formData
//    ) {
//        boolean result = tasktableService.updateTasktable(id, formData);
////        return Result.judge(result);
////    }
//
//    @Operation(summary = "删除")
//    @DeleteMapping("/{ids}")
////    @PreAuthorize("@ss.hasPerm('system:tasktable:delete')")
//    public Result<Void> deleteTasktables(
//            @Parameter(description = "首页ID，多个以英文逗号(,)分割") @PathVariable String ids
//    ) {
//        boolean result = tasktableService.deleteTasktables(ids);
//        return Result.judge(result);
//    }
////    @PostMapping("/{id}/staTime")
////    public Result<?> setActyalStrtIme(@PathVariable Integer id, @RequestBody LocalDateTime commencement){
////        try {
////            taskTableService.calculateRemainingTime(id, commencement);
////            return Result.success();
////        }catch (Exception e){
////            return Result.fail("500","设置实际开始时间失败");
////        }
////    }

    /**
     * 归档接口
     *
     * @param archive
     * @return
     */
    @PutMapping("/{id}/archive")
    public Result<Void> updateArchiveStatus(@PathVariable Long id, @RequestParam Integer archive) {
        if (archive != 0 && archive != 1) {
            return Result.error("nvalid archive status. Must be 0 or 1.");
        }
        boolean result = tasktableService.updateArchive(id, archive);
        if (result) {
            return Result.success("Update successful.");
        } else {
            return Result.error("Failed to update archive status.");
        }
    }

//    /**
//     * 批量归档接口
//     */
//    @PutMapping("/batch")
//    public Result<Void> batchUpdateArchiveStatus(@RequestBody BatchUpdateRequest request) {
//        if (request.getId() == null || request.getId().isEmpty()
//                || (request.getArchive() != 0 && request.getArchive() != 1)) {
//            return Result.error("Invalid input.");
//        }
//
//        boolean result = tasktableService.batchUpdateArchiveStatus(request.getId(), request.getArchive());
//        if (result) {
//            return Result.success("Batch update successful.");
//        } else {
//            return Result.error("Failed to batch update archive status.");
//        }
//    }

    /**
     * 根据归档为1查询
     *
     * @return
     */
    @GetMapping("/archivetasks")
    public PageResult<TaskTableVO> getArchiveTasks(TaskTableQuery queryParams) {
        IPage<TaskTableVO> result = tasktableService.getArchivePage(queryParams);
        return PageResult.success(result);
//        return Result.success(tasktableService.getArchiveTasks());
    }

    /**
     * 获取任务完成情况统计数据
     *
     * @return
     */
    @GetMapping("/completion-ratio")
    public Result<List<Map<String, Object>>> getTaskCompletionRatio() {
        return Result.success(tasktableService.getTaskCompletionCount());
    }

    /**
     * 统计过去七天新增的任务数量
     * @return 任务数量
     */
    @GetMapping("/sevenDays")
    public Result<Integer> countTasksInLastSevenDays() {
        return Result.success(tasktableService.countTasksInLastSevenDays());
    }
}
